﻿using FYSJcrm.Core.Common;
using FYSJcrm.Core.IRepository.SystemManage;
using FYSJcrm.Core.Web.Areas.SystemManage.Models.SystemManageModels;
using FYSJcrm.Core.Web.Extensions.FilterExtensions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace FYSJcrm.Core.Web.Areas.SystemManage.Controllers
{
    [Area(nameof(SystemManage))]
    public class SystemLogController : Controller
    {
        private readonly ISystemLogRepository _systemLogRepository;

        public SystemLogController(ISystemLogRepository systemLogRepository)
        {
            _systemLogRepository = systemLogRepository;
        }

        [CheckPermission("SystemLog.Show")]
        public IActionResult List()
        {
            return View();
        }

        [CheckPermission("SystemLog.Show")]
        public async Task<IActionResult> ListData(int page = 1, int limit = 10)
        {
            var sysLogs = await _systemLogRepository.Select.OrderByDescending(p => p.AddTime)
                .LeftJoin(p => p.Manager.Id == p.UserId)
                .Count(out long total)
                .Page(page, limit)
                .ToListAsync<SystemLogViewModel>();

            return Json(new AjaxResult { Code = HttpCode.OK, Data = sysLogs, TotalCount = total });
        }

        [HttpPost]
        [CheckPermission("SystemLog.Delete")]
        public async Task<IActionResult> BatchDelete()
        {
            var count = await _systemLogRepository.DeleteAsync(p => p.AddTime.AddDays(7).Subtract(DateTime.Now).Days < 0);

            return count > 0 ? Json(new AjaxResult { Code = HttpCode.OK, Data = "删除日志成功！" })
                : Json(new AjaxResult { Code = HttpCode.BadRequest, ErrorMsg = "删除日志失败！" });
        }
    }
}
